//
//  LXLOAuthViewController.swift
//  Weibo-YQY-test
//
//  Created by Lang on 10/14/15.
//  Copyright © 2015 Lang. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class LXLOAuthViewController: UIViewController, UIWebViewDelegate {
    
    //申请应用时分配的AppKey
    let CLIENT_ID = "2797570396"
    //App Secret：ba3fc8704d2198488eb96cc03d013e63
    let APP_SECRET = "ba3fc8704d2198488eb96cc03d013e63"
    
    //回调地址
    let REDIRECT_URL = "http://www.baidu.com/"
    
    var webView: UIWebView?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //添加导航栏的自动填充按钮
        setupNav()

        //给用户提供一个登录的界面
        //用 webView加载
        let webView = UIWebView(frame: UIScreen.mainScreen().bounds)
        
        webView.delegate = self
        
        //拼接URL
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(CLIENT_ID)&redirect_uri=\(REDIRECT_URL)"
        // 初始化一个 url
        let url = NSURL(string: urlString)
        // 初始化一个 request
        let request = NSURLRequest(URL: url!)
        //加载请求
        webView.loadRequest(request)
        
        //添加 webView
        view.addSubview(webView)
        self.webView = webView
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    func setupNav(){
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    
    @objc private func autoFill(){
        let script = "document.getElementById('userId').value='my5136@sina.com';document.getElementById('passwd').value='lilang+1991'"
        self.webView?.stringByEvaluatingJavaScriptFromString(script)
    }

    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 监听 webView 加载的是哪一个地址，如果发现是回调页，查看是否带有 code,如果有 code，截取 code，获取 accessToken
        let urlString = request.URL?.absoluteString
        //hasPrefix:方法的功能是判断创建的字符串内容是否以某个字符开始
        if urlString!.hasPrefix(REDIRECT_URL){
            //查看是否带有 code
            let codePre = "code="
            
            let range = (urlString! as NSString).rangeOfString(codePre)
            if range.location != NSNotFound{
                
                //能进入到这里面，就证明回调地址里面有 code=
                let code = (urlString! as NSString).substringFromIndex(range.location + range.length)
                // 获得到了 code
                printLog("code = \(code)")
                //请访问令牌
                loadAccessToken(code)
                return false
            }
        }
        
        printLog("回调地址:\(urlString)")
        
        return true
    }
    
    // 获取 accessToken
    private func loadAccessToken(code:String){
        // 要用到 afn
        let manager = AFHTTPSessionManager()
        // 给默认的序列化器添加一个可以接受的内容类型
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //参数
        let params = [
            "client_id":CLIENT_ID,
            "client_secret":APP_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URL
        ]
        
        // 发送请求
        manager.POST(urlString, parameters: params, success: { (datatask, result) -> Void in
            // 请求成功的闭包
            printLog("请求成功:\(result)")
            
            //字典转模型
            if let res = (result as? [String: AnyObject]){
                let account = LXLUserAccount(dictionary: res)
                
                // 获取个人信息
                self.loadUserInfo(account)
            }
            
            
            
            }) { (datatask, error) -> Void in
                printLog("请求失败：\(error)")
                //请求失败
                SVProgressHUD.dismiss()
        }
        
        
    }
    
    
    // 获取个人信息
    private func loadUserInfo(account:LXLUserAccount){
        // 初始化一个 session请求的管理者
        let manager = AFHTTPSessionManager()
        
        //请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        //拼装参数
        let params = [
            "access_token":account.access_token!,
            "uid":account.uid!
        ]
        
        //发送 get 请求
        manager.GET(urlString, parameters: params, success: { (dataTask, result) -> Void in
            //请求成功
            
            if let res = (result as? [String: AnyObject]){
                //获取头像
                account.avatar_large = res["avatar_large"] as? String
                //获取昵称
                account.name = res["name"] as? String
                
                account.saveAccount()
                
                //登录成功后消失弹窗
                SVProgressHUD.dismiss()
                
                //登录成功后----> 欢迎页
                LXLUserAccount.isLogin(loginSuccess: LXLWelcomeViewController())
                
            }
            
            
            }) { (dataTask, error) -> Void in
                //请求失败
                SVProgressHUD.dismiss()
        }
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
